package server;

import org.w3c.dom.NodeList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by swootton on 27/02/14.
 */
public class RepositoryServlet extends MFHttpServlet {

    private Connection connection;

    public RepositoryServlet(){

    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("RepositoryServlet.doPost()"+"\n");

        //connection = (Connection) request.getAttribute("db_connection");
        connection = (Connection) getServletContext().getAttribute("db_connection");

        NodeList nList = (NodeList) request.getAttribute("request_xml");

        System.out.println("RepositoryServlet.nodeList"+nList.item(0).getAttributes().getNamedItem("type"));

        doRepositoryRequest(request, response);

        connection = null;
    }

    // TODO do no update registered field (currently happens automatically due to UPDATE on schema

    public void doRepositoryRequest(HttpServletRequest request, HttpServletResponse response) {

        /**
         *  +-------------------+-------------+------+-----+---------+----------------+
         | Field             | Type        | Null | Key | Default | Extra          |
         +-------------------+-------------+------+-----+---------+----------------+
         | id                | int(11)     | NO   | PRI | NULL    | auto_increment |
         | name              | text        | NO   |     | NULL    |                |
         | library_url       | text        | NO   |     | NULL    |                |
         | library_path      | text        | NO   |     | NULL    |                |
         | url_auth_username | text        | NO   |     | NULL    |                |
         | url_auth_password | varchar(32) | NO   |     | NULL    |                |
         +-------------------+-------------+------+-----+---------+----------------+

         */

        // TODO should these be stored in session to prevent query everytime we upload or download?
        // have to know destination for nearly all actions

        // library_url, library_path, url_auth_username, url_auth_password

        String REPOSITORY_REQ_QUERY = "SELECT name FROM mf_repositories;";

        StringBuilder strResp = new StringBuilder();

        strResp.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
        strResp.append("<MFResponse>\n");
        strResp.append("<Response type='Repositories'>\n");

        String name = "";

        try {
            //Class.forName("com.mysql.jdbc.Driver");  //registering the jdbc driver here

            //db_con = DriverManager.getConnection(db_url, db_user, db_pwd);
            Statement db_st = connection.createStatement();
            ResultSet db_rs = db_st.executeQuery(REPOSITORY_REQ_QUERY);

            while (db_rs.next()) {

                name = db_rs.getString(1);

                strResp.append("<Repository name='"+name+"' creator='' num_genres='' num_songs='' members=''/>"+"\n");
            }
        }
        /*catch(ClassNotFoundException e1) {

            System.out.println(e1.getMessage());
            e1.printStackTrace();
        }*/
        catch (SQLException e2) {

            System.out.println(e2.getMessage());
            e2.printStackTrace();
        }

        strResp.append("</Response>\n");
        strResp.append("</MFResponse>\n");

        // TODO check for better query failing

        if(name.equals("")) {
            writeErrorResponse(request, response, "ERROR_WITH_MF_SERVER");
        } else {
            write(response, strResp);
        }
    }
}
